﻿using System;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using System.Linq;

namespace Table_Storage_Component
{
    partial class ComponentUIForm :  System.Windows.Forms.Form
    {
        private System.ComponentModel.IContainer components = null;
        private Connections connections;
        private Variables variables;
        private IDTSComponentMetaData100 metaData;
        private CManagedComponentWrapper designTimeInstance;
        private TextBox TXT_ConnectionString;
        private Label ConnectionStringText;
        private Label label1;
        private Label label2;
        private TextBox TXT_DateFilter;
        private Label ErrorLBL;
        private ComboBox tableCmbx;
        private Button btnOk;
        private CloudStorageAccount cloudStorageAccount;
        private Button RefreshBttn;
        private Button CancelBttn;
        private Label label3;
        private ToolTip ConnectionStringTLT;
        private ToolTip DateFilterTLT;
        private Button AboutBttn;
        private CloudTableClient TableClient;


        public ComponentUIForm(Connections cons, Variables vars, IDTSComponentMetaData100 md, IServiceProvider serviceProvider)
        {
            variables = vars;
            connections = cons;
            metaData = md;
            designTimeInstance = md.Instantiate();
            this.InitializeComponent();

        }
        
        private void btnOk_Click(object sender, System.EventArgs e)
        {
            if (this.ValidateForm())
            {
                designTimeInstance.SetComponentProperty("StorageConnectionString", TXT_ConnectionString.Text);
                designTimeInstance.SetComponentProperty("TableName", tableCmbx.SelectedItem.ToString());
                designTimeInstance.SetComponentProperty("FiltreDate", TXT_DateFilter.Text);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }
        private void PopulateControls()
        {
            this.TXT_ConnectionString.Text = metaData.CustomPropertyCollection["StorageConnectionString"].Value;

            //this.tableCmbx.Items.Add(metaData.CustomPropertyCollection["TableName"].Value);
            this.TXT_DateFilter.Text = metaData.CustomPropertyCollection["FiltreDate"].Value;
        }
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ComponentUIForm));
            this.TXT_ConnectionString = new System.Windows.Forms.TextBox();
            this.ConnectionStringText = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.TXT_DateFilter = new System.Windows.Forms.TextBox();
            this.ErrorLBL = new System.Windows.Forms.Label();
            this.btnOk = new System.Windows.Forms.Button();
            this.tableCmbx = new System.Windows.Forms.ComboBox();
            this.RefreshBttn = new System.Windows.Forms.Button();
            this.CancelBttn = new System.Windows.Forms.Button();
            this.label3 = new System.Windows.Forms.Label();
            this.ConnectionStringTLT = new System.Windows.Forms.ToolTip(this.components);
            this.DateFilterTLT = new System.Windows.Forms.ToolTip(this.components);
            this.AboutBttn = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // TXT_ConnectionString
            // 
            this.TXT_ConnectionString.Location = new System.Drawing.Point(116, 76);
            this.TXT_ConnectionString.Name = "TXT_ConnectionString";
            this.TXT_ConnectionString.Size = new System.Drawing.Size(459, 20);
            this.TXT_ConnectionString.TabIndex = 0;
            this.ConnectionStringTLT.SetToolTip(this.TXT_ConnectionString, "DefaultEndpointsProtocol=[http|https];AccountName=myAccountName;AccountKey=myAcco" + "untKey");
            // 
            // ConnectionStringText
            // 
            this.ConnectionStringText.AutoSize = true;
            this.ConnectionStringText.Location = new System.Drawing.Point(13, 79);
            this.ConnectionStringText.Name = "ConnectionStringText";
            this.ConnectionStringText.Size = new System.Drawing.Size(97, 13);
            this.ConnectionStringText.TabIndex = 1;
            this.ConnectionStringText.Text = "Connection String: ";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(13, 117);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(68, 13);
            this.label1.TabIndex = 3;
            this.label1.Text = "Table Name:";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(13, 159);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(61, 13);
            this.label2.TabIndex = 5;
            this.label2.Text = "Date Filter: ";
            // 
            // TXT_DateFilter
            // 
            this.TXT_DateFilter.Location = new System.Drawing.Point(116, 156);
            this.TXT_DateFilter.Name = "TXT_DateFilter";
            this.TXT_DateFilter.Size = new System.Drawing.Size(316, 20);
            this.TXT_DateFilter.TabIndex = 4;
            this.DateFilterTLT.SetToolTip(this.TXT_DateFilter, "DD/MM/YYYY HH:MM:SS");
            // 
            // ErrorLBL
            // 
            this.ErrorLBL.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(24)))), ((int)(((byte)(0)))), ((int)(((byte)(150)))));
            this.ErrorLBL.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.ErrorLBL.Location = new System.Drawing.Point(14, 196);
            this.ErrorLBL.Name = "ErrorLBL";
            this.ErrorLBL.Size = new System.Drawing.Size(600, 40);
            this.ErrorLBL.TabIndex = 6;
            // 
            // btnOk
            // 
            this.btnOk.ForeColor = System.Drawing.Color.Black;
            this.btnOk.Location = new System.Drawing.Point(427, 249);
            this.btnOk.Name = "btnOk";
            this.btnOk.Size = new System.Drawing.Size(75, 23);
            this.btnOk.TabIndex = 7;
            this.btnOk.Text = "OK";
            this.btnOk.UseVisualStyleBackColor = true;
            this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
            // 
            // tableCmbx
            // 
            this.tableCmbx.FormattingEnabled = true;
            this.tableCmbx.Location = new System.Drawing.Point(116, 114);
            this.tableCmbx.Name = "tableCmbx";
            this.tableCmbx.Size = new System.Drawing.Size(390, 21);
            this.tableCmbx.TabIndex = 8;
            this.tableCmbx.Click += new System.EventHandler(this.tableCmbx_Click);
            // 
            // RefreshBttn
            // 
            this.RefreshBttn.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("RefreshBttn.BackgroundImage")));
            this.RefreshBttn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.RefreshBttn.Location = new System.Drawing.Point(581, 76);
            this.RefreshBttn.Name = "RefreshBttn";
            this.RefreshBttn.Size = new System.Drawing.Size(18, 20);
            this.RefreshBttn.TabIndex = 9;
            this.RefreshBttn.UseVisualStyleBackColor = true;
            this.RefreshBttn.Click += new System.EventHandler(this.RefreshBttn_Click);
            // 
            // CancelBttn
            // 
            this.CancelBttn.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.CancelBttn.ForeColor = System.Drawing.Color.Black;
            this.CancelBttn.Location = new System.Drawing.Point(513, 249);
            this.CancelBttn.Name = "CancelBttn";
            this.CancelBttn.Size = new System.Drawing.Size(75, 23);
            this.CancelBttn.TabIndex = 10;
            this.CancelBttn.Text = "Cancel";
            this.CancelBttn.UseVisualStyleBackColor = true;
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 18F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label3.Location = new System.Drawing.Point(12, 18);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(317, 29);
            this.label3.TabIndex = 11;
            this.label3.Text = "Azure Table Storage Source";
            // 
            // AboutBttn
            // 
            this.AboutBttn.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.AboutBttn.ForeColor = System.Drawing.Color.Black;
            this.AboutBttn.Location = new System.Drawing.Point(599, 249);
            this.AboutBttn.Name = "AboutBttn";
            this.AboutBttn.Size = new System.Drawing.Size(24, 23);
            this.AboutBttn.TabIndex = 12;
            this.AboutBttn.Text = "?";
            this.AboutBttn.UseVisualStyleBackColor = true;
            this.AboutBttn.Click += new System.EventHandler(this.AboutBttn_Click);
            // 
            // ComponentUIForm
            // 
            this.AcceptButton = this.btnOk;
            this.AccessibleName = "Azure Table Storage Source";
            this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(24)))), ((int)(((byte)(0)))), ((int)(((byte)(82)))));
            this.CancelButton = this.CancelBttn;
            this.ClientSize = new System.Drawing.Size(634, 286);
            this.Controls.Add(this.AboutBttn);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.CancelBttn);
            this.Controls.Add(this.RefreshBttn);
            this.Controls.Add(this.tableCmbx);
            this.Controls.Add(this.btnOk);
            this.Controls.Add(this.ErrorLBL);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.TXT_DateFilter);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.ConnectionStringText);
            this.Controls.Add(this.TXT_ConnectionString);
            this.ForeColor = System.Drawing.Color.White;
            this.MaximizeBox = false;
            this.MaximumSize = new System.Drawing.Size(650, 325);
            this.MinimizeBox = false;
            this.MinimumSize = new System.Drawing.Size(650, 325);
            this.Name = "ComponentUIForm";
            this.Text = "Azure Table Storage Source";
            this.Load += new System.EventHandler(this.ComponentUIForm_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private void ComponentUIForm_Load(object sender, EventArgs e)
        {
            PopulateControls();
            //PopulateTables();
        }
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
        public bool ValidateForm()
        {
            // Validate that there is one input.
            if (metaData.OutputCollection.Count < 1)
            {
                ErrorLBL.Text = "The Table should have at least 1 Colum";
                return false;
            }
            ErrorLBL.Text = String.Empty;
            return true;
        }

        public bool PopulateTables()
        {


            tableCmbx.Items.Clear();
            try
            {
                cloudStorageAccount = CloudStorageAccount.Parse(TXT_ConnectionString.Text);

                TableClient = cloudStorageAccount.CreateCloudTableClient();
                TableClient.RetryPolicy = RetryPolicies.Retry(4, TimeSpan.Zero);

                IEnumerable<string> tables = TableClient.ListTables();
                if (tables != null && tables.Any())
                {
                    foreach (string tableName in tables)
                    {
                        tableCmbx.Items.Add(tableName);
                    }
                    tableCmbx.SelectedIndex = 0;
                }
                if (!string.IsNullOrEmpty(metaData.CustomPropertyCollection["TableName"].Value))
                {
                    int present = tableCmbx.FindString(metaData.CustomPropertyCollection["TableName"].Value);
                    if (present != -1)
                    {
                        tableCmbx.SelectedIndex = present;
                    }
                }
                ErrorLBL.Text = string.Empty;
                return true;
                
            }
            catch (Exception ex)
            {
                setErrorMessage("Connection Fail, check your connection String : DefaultEndpointsProtocol=https;AccountName=name;AccountKey=key");
                return false;
            }
        }

        public void setErrorMessage(string message)
        {
            ErrorLBL.Text = message;
        }

        private void RefreshBttn_Click(object sender, EventArgs e)
        {
            PopulateTables();
        }

        private void AboutBttn_Click(object sender, EventArgs e)
        {
            // Create and display the form for the user interface.
            AboutForm aboutForm = new AboutForm();
            aboutForm.StartPosition = FormStartPosition.CenterParent;
            aboutForm.ShowDialog();
            this.DialogResult = DialogResult.None;

        }

        private void tableCmbx_Click(object sender, EventArgs e)
        {
            PopulateTables();
        }



    }
}
